package tman.simulator.snapshot;

import java.util.HashMap;
import java.util.Set;

public class CentralSolution {

	HashMap<Integer, Integer> resources;
	HashMap<Integer, Integer> HopCountDistr;
	
	public CentralSolution()
	{
		resources = new HashMap<Integer, Integer>();
		HopCountDistr = new HashMap<Integer, Integer>();
	}
	
	public void addNodes(Integer outdegree, Integer quantity)
	{
		resources.put(outdegree, quantity);
	}
	
	public void startAndRun()
	{
		Integer max = MaxOD();
		resources.put(max, resources.get(max)-1);
		Integer counter = 1;
		Integer[] returns = ConsumeNodes(max);
		HopCountDistr.put(0, 1);
		HopCountDistr.put(1, returns[0]);
		while(!resources.isEmpty())
		{
			counter++;
			returns = ConsumeNodes(returns[1]);
			HopCountDistr.put(counter, returns[0]);
		}
	}
	
	public HashMap<Integer, Integer> getDistr()
	{
		return HopCountDistr;
	}
	
	public Integer[] ConsumeNodes(Integer quantity)
	{
		Integer[] returns = new Integer[2];
		Integer consumed = 0;
		Integer availConnections = 0;
		while(quantity!=0)
		{
			Integer max=MaxOD();
			Integer available = resources.get(max);
			if(available != null)
			{
				if(quantity<available)
				{
					resources.put(max, available-quantity);
					consumed = consumed + quantity;
					availConnections = availConnections + quantity * max;
					quantity = 0;
					
				}
				else if (quantity==available)
				{
					resources.remove(max);
					consumed = consumed + quantity;
					availConnections = availConnections + quantity * max;
					quantity = 0;
				}
				else {
					resources.remove(max);
					availConnections = availConnections + available * max;
					consumed = consumed + available;
					quantity = quantity - available;
				}
			}
			else break;
		}
		returns[0] = consumed;
		returns[1] = availConnections;
		return returns;
	}
	
	public Integer MaxOD()
	{
		Integer max=0;
		Integer[] degrees = resources.keySet().toArray(new Integer[0]);
		for(int i=0; i<degrees.length; i++)
		{
			if(degrees[i]>max)
				max = degrees[i];
		}
		return max;
	}
	
	

}
